#include<bits/stdc++.h>
using namespace std;
struct ios{
    inline char gc(){
        static const int IN_LEN=1<<18|1;
        static char buf[IN_LEN],*s,*t;
        return (s==t)&&(t=(s=buf)+fread(buf,1,IN_LEN,stdin)),s==t?-1:*s++;
    }
    template <typename _Tp> inline ios & operator >> (_Tp&x){
        static char ch,sgn; ch = gc(), sgn = 0;
        for(;!isdigit(ch);ch=gc()){if(ch==-1)return *this;sgn|=ch=='-';}
        for(x=0;isdigit(ch);ch=gc())x=x*10+(ch^'0');
        sgn&&(x=-x); return *this;
    }
}io;
#define cin io
mt19937 Rnd(time(0));
int T,mod,n;
typedef struct{
	int a[1011][1011];
}AD;
AD emt;
void tms(AD& res,AD A,AD B)
{
	res = emt;
	for(int i = 0,j = 0;j < n;j++)
		for(int k = 0;k < n;k++)
			(res.a[i][j] += (1ll * A.a[i][k] * B.a[k][j] % mod)) %= mod;
}
AD A,B,C,X,L,R;
int main()
{
	freopen("matrix.in","r",stdin);
	freopen("matrix.out","w",stdout);
	cin >> T;
	while(T--)
	{
		cin >> mod >> n;
		for(int i = 0;i < n;i++)
			for(int j = 0;j < n;j++)
				cin >> A.a[i][j];
		for(int i = 0;i < n;i++)
			for(int j = 0;j < n;j++)
				cin >> B.a[i][j];
		for(int i = 0;i < n;i++)
			for(int j = 0;j < n;j++)
				cin >> C.a[i][j];
		bool flag = 0;
		int K = 5;
		while(K--)
		{
			for(int i = 0;i < n;i++)
				X.a[0][i] = Rnd() % mod;
			tms(L,X,A),tms(L,L,B);
			tms(R,X,C);
			for(int i = 0;i < n;i++) if(L.a[0][i] != R.a[0][i])
				flag = 1;
		}
		if(flag)
			printf("No\n");
		else
			printf("Yes\n");
	}
	return 0;
}
